package com.yazi.mxz.mobile.common;


import javax.annotation.Resource;
import com.myframework.smhj.common.tool.DateUtil;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.realm.AuthorizingRealm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yazi.mxz.common.MyUtil;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.service.MemberService;

/**
 * 
 * 
 * @author mo_yq5@163.com
 * @date 2013-11-22
 * 
 */
public abstract class AbstractRealm extends AuthorizingRealm {
	private static Logger log = LoggerFactory.getLogger(AbstractRealm.class);
	@Resource
	MemberService memberService;
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0)
			throws AuthenticationException {

		String password = new String((char[]) arg0.getCredentials());
		String name = String.valueOf(arg0.getPrincipal());
		Member member = memberService.oneByAccountName(name);
		if (null == member) {
			throw new AuthenticationException("用户不存在");
		}
		if (!MyUtil.checkPwd(member, password)) {
			throw new AuthenticationException("密码不正确");
		}

		// 更新登录时间
		member.setLoginTime(DateUtil.getTimeStamp());
		member = memberService.merge(member);

		log.debug("用户认证通过：name={}", member.getName());
		
		return getMyAuthenticationInfo(member, password);
	}
	
	public abstract AuthenticationInfo getMyAuthenticationInfo(Member member, String password);

}
